package common.web.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.alibaba.fastjson.JSONObject;

import common.hibernate.service.BaseService;
import common.log.service.LogService;
import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.Account;
import common.rbac.po.Admin;
import common.rbac.po.User;
import common.rbac.po.UserGroup;
import common.rbac.po.UserRole;
import common.util.JSONUtils;
import common.util.UUIDUtil;
import common.web.vo.Result;

@SuppressWarnings("deprecation")
@Controller
@RequestMapping("/system/user")
public class UserAction extends MultiActionController {
	

	@Autowired(required=false)
	PasswordEncoder encoder;
	
	@Autowired
	@Qualifier("baseServiceImpl")
	protected BaseService baseService;
	
	@Autowired
	private LogService logService;

	@RequestMapping("/view/{id}")
	@ResponseBody
	public Result view(@PathVariable String id) {
		User user = this.baseService.get(User.class, id);
		if(null == user) {
			return Result.fail("用户不存在");
		}
		
		Result res = Result.createResult(user);
		
		UserRole ur = new UserRole();
		ur.setUserId(user.getId());
		UserGroup ug = new UserGroup();
		ug.setUserId(user.getId());
		res.addMap("roles", baseService.findByExample(ur));
		res.addMap("groups", baseService.findByExample(ug));
		
		return res;
	}
	
	@RequestMapping("/list/{isAdmin}")
	@ResponseBody
	public Result list(@PathVariable String isAdmin) {
		List<? extends User> list = null;
		if ("isAdmin".equals(isAdmin)) {
			list = baseService.loadAll(Admin.class);
		} else {
			list = baseService.loadAll(Account.class);
		}
		return Result.createResult(list);
	}
	

	@RequestMapping("/{editType}/{isAdmin}")
	@ResponseBody
	public Result save(@PathVariable String editType, @PathVariable String isAdmin, @RequestBody JSONObject json) {
		JSONObject ju = json.getJSONObject("entity");
		User user = null;
		if ("isAdmin".equals(isAdmin)) {
			user = JSONUtils.toJavaObject(ju, Admin.class);
		} else {
			user = JSONUtils.toJavaObject(ju, Account.class);
		}
		List<UserGroup> ugs = JSONUtils.toJavaObject(json.getJSONArray("groups"), UserGroup.class);
		List<UserRole> urs = JSONUtils.toJavaObject(json.getJSONArray("roles"), UserRole.class);
		
		if (null != user) {
			WebLog log = new WebLog(LogModule.USER, LogType.ADD, "操作失败");
			if("update".equals(editType)) {
				log.setType(LogType.UPDATE);
			}
			try {
				List<Object> saves = new ArrayList<Object>();
				saves.addAll(ugs);
				saves.addAll(urs);
				
				List<Object> deletes = new ArrayList<>();
				
				UserGroup ug = new UserGroup();
				ug.setUserId(user.getId());
				UserRole ur = new UserRole();
				ur.setUserId(user.getId());
				
				// 删除关联部分
				deletes.addAll(baseService.findByExample(ug));
				deletes.addAll(baseService.findByExample(ur));
				
				if ("update".equals(editType)) {
					baseService.dbOperation(saves.toArray(), new Object[]{user}, deletes.toArray());
					
					log.setSuccess(MessageFormat.format("修改用户[{0}]成功!", user.getName()));
				} else if ("add".equals(editType)) {
					user.setId(UUIDUtil.createUuid());
					
					for (UserRole urf : urs) {
						urf.setUserId(user.getId());
					}
					for (UserGroup ugf : ugs) {
						ugf.setUserId(user.getId());
					}
					user.setCreateDt(new Date());
					user.setEnabled(true);
					user.setNonLock(true);
					saves.add(user);
					
					if(null != encoder) {
						user.setPassword(encoder.encodePassword(user.getPassword(), null));
					}
					
					baseService.dbOperation(saves.toArray(), null, deletes.toArray());
					
					log.setSuccess(MessageFormat.format("新增用户[{0}]成功!", user.getName()));
				}
			} catch (Exception e) {
				log.setFail(MessageFormat.format("新增用户[{0}]失败!", user.getName()));
				logger.error("", e);
				
				return Result.fail("数据错误，请刷新后重试");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}
	
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Result delete(@PathVariable String id) {
		User load = baseService.load(User.class, id);
		if(null != load) {
			WebLog log = new WebLog(LogModule.USER, LogType.DELETE, "操作失败");
			try {
				List<Object> deletes = new ArrayList<>();
				
				// 关联的查询出来一起删除
				UserGroup ug = new UserGroup();
				ug.setUserId(load.getId());
				UserRole ur = new UserRole();
				ur.setUserId(load.getId());
				
				// 删除关联部分
				deletes.addAll(baseService.findByExample(ug));
				deletes.addAll(baseService.findByExample(ur));
				deletes.add(load);
				
				baseService.delete(deletes.toArray());
				
				// 日志
				log.setSuccess(MessageFormat.format("删除用户[{0}]成功!", load.getName()));
			} catch (Exception e) {
				log.setFail(MessageFormat.format("删除用户[{0}]失败!", load.getName()));
				logger.error("", e);
				
				return Result.fail("删除失败");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("用户不存在");
		}
		return Result.SUCCESS;
	}
}
